package ch.zbw.pra.sysventory.business.businessObject.scan;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import ch.zbw.pra.sysventory.model.HardDisk;

import com.jacob.activeX.ActiveXComponent;
import com.jacob.com.Dispatch;
import com.jacob.com.EnumVariant;
import com.jacob.com.Variant;

/**
 * Gibt alle HardDisk mittels WMI Schnittstelle auf einem bestimmten Host zurück
 * 
 * @author Ralph Koster
 */

public class ScanHardDiskBusinessObject implements Serializable {

	private static final long serialVersionUID = 9004201131500876765L;
	private static Logger LOG = LoggerFactory.getLogger(ScanHardDiskBusinessObject.class);
	
	private List<HardDisk> hardDisks;


	public ScanHardDiskBusinessObject() {
		this.hardDisks = new ArrayList<HardDisk>();
	}

	public List<HardDisk> getAllHardDisksFromHost(String host) {
		String connectStr = String.format("winmgmts:\\\\%s\\root\\CIMV2", host);
		String query = "SELECT * FROM win32_Volume";
		try {
			ActiveXComponent axWMI = new ActiveXComponent(connectStr);
			// Execute the query
			Variant vCollection = axWMI.invoke("ExecQuery", new Variant(query));

			// Das Resultat ist eine Datensammlung
			EnumVariant enumVariant = new EnumVariant(vCollection.toDispatch());
			Dispatch item = null;

			while (enumVariant.hasMoreElements()) {

				item = enumVariant.nextElement().toDispatch();
				// Dispatch.call returns a Variant which we can convert to a java form.
				
				String driveLetter = Dispatch.call(item, "DriveLetter").toString();
				Long tempHardDiskCapacity = Long.valueOf(Dispatch.call(item, "Capacity").toString());
				Long tempHardDiskFreeSpace = Long.valueOf(Dispatch.call(item, "FreeSpace").toString());
				String hardDiskCapacity = String.valueOf(tempHardDiskCapacity / 1073741824) + " GB";
				String hardDiskFreeSpace = String.valueOf(tempHardDiskFreeSpace / 1073741824) + " GB";
				String hardDiskEfficiency = (tempHardDiskCapacity - tempHardDiskFreeSpace) / 1073741824 + " GB";
				
				LOG.debug("HardDisk found: " + driveLetter + " " + hardDiskCapacity + " "
						+ hardDiskFreeSpace + " " + hardDiskEfficiency);

				if(null != driveLetter && !"null".equals(driveLetter) && !"".equals(driveLetter)) {
					HardDisk hardDisk = new HardDisk(driveLetter, hardDiskCapacity, 
												hardDiskFreeSpace, hardDiskEfficiency);
					hardDisks.add(hardDisk);
				}
			}
		} catch (Exception e) {
			LOG.debug("Failed to load hardDisks from host: " + host);
			LOG.error(e.toString());
		}
		return hardDisks;
	}
}
